<?php
require __DIR__ . '/config/config.php';

function getRandomImage() {
    $images = array_diff(scandir(IMAGE_DIR), array('..', '.'));
    $randomImage = $images[array_rand($images)];
    return [
        'full_path' => realpath(IMAGE_DIR . '/' . $randomImage),
        'filename' => $randomImage
    ];
}

function checkCache($request_id) {
    if (file_exists(CACHE_FILE)) {
        $cache_data = file(CACHE_FILE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($cache_data as $line) {
            $cached = json_decode($line, true);
            if ($cached['request_id'] === $request_id) {
                if (time() - $cached['timestamp'] < CACHE_TIME) {
                    return [
                        'full_path' => $cached['full_path'],
                        'filename' => $cached['filename']
                    ];
                }
                $cache_data = array_filter($cache_data, function($l) use ($line) {
                    return $l !== $line;
                });
                file_put_contents(CACHE_FILE, implode(PHP_EOL, $cache_data) . PHP_EOL);
                break;
            }
        }
    }
    return null;
}

function setCache($request_id, $image_data) {
    $cache_entry = json_encode([
        'request_id' => $request_id,
        'timestamp' => time(),
        'full_path' => $image_data['full_path'],
        'filename' => $image_data['filename']
    ]);
    file_put_contents(CACHE_FILE, $cache_entry . PHP_EOL, FILE_APPEND);
}

$client_ip = $_SERVER['REMOTE_ADDR'];
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $client_ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
}

$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$request_id = md5($client_ip . $referer . $_SERVER['REQUEST_URI']);

$cached_image = checkCache($request_id);

if ($cached_image) {
    $response_image = $cached_image;
} else {
    $response_image = getRandomImage();
    setCache($request_id, $response_image);
}

if (!file_exists($response_image['full_path'])) {
    http_response_code(404);
    exit;
}

$type = isset($_GET['type']) ? $_GET['type'] : '';

if ($type === 'json') {
    header('Content-Type: application/json');
    echo json_encode([
        'image' => '/images/' . $response_image['filename']
    ]);
} else {
    if (ob_get_length()) {
        ob_clean();
    }
    header('Content-Type: image/jpeg');
    readfile($response_image['full_path']);
}
?>